<template id="EditUserInfoModal">
  <a-modal
    v-model:open="openEditModal"
    title="编辑用户信息"
    :footer="null"
    width="700px"
    style="top: 20px"
    destroyOnClose
    @cancel="handleCloseModal"
  >
    <div class="edit-card" style="margin-top: 20px">
      <div class="edit-card-content">
        <a-form :model="userInfo" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
          <a-form-item label="账号">
            <a-input
              v-model:value="userInfo.userAccount"
              show-count
              :maxlength="20"
              :disabled="true"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="用户名">
            <a-input v-model:value="userInfo.userName" allow-clear />
          </a-form-item>
          <a-form-item label="头像">
            <!-- <a-input v-model:value="userInfo.userAvatar" /> -->
            <UploadImage v-model:fileUrl="userInfo.userAvatar" />
            <!-- 预览图 -->
            <!-- <p class="edit-card-image" style="background-color: #FAFAFA; margin-top: 10px;padding: 0px 20px;box-shadow: 0 0 5px #ccc;">
              <a-image
                :src="userInfo.userAvatar"
                style="width: 100px; height: 100px; margin-top: 10px"
              ></a-image>
              <p style="font-size: 12px; color: #999;">支持图片链接，建议尺寸：400 x 300</p>
            </p> -->
          </a-form-item>
          <a-form-item label="简介">
            <a-input v-model:value="userInfo.userProfile" allow-clear />
          </a-form-item>

          <a-form-item label="用户角色" v-if="isAdmin">
            <!-- <a-input v-model:value="userInfo.userRole" :disabled="true" /> -->
            <a-select
              v-model:value="userInfo.userRole"
              show-search
              :options="selectOptions"
            ></a-select>
          </a-form-item>
        </a-form>
      </div>
      <div class="edit-footer-btn" style="text-align: center">
        <a-space>
          <a-button type="primary" @click="handleEditUser" :loading="loading">保存修改</a-button>
          <a-button type="default" @click="handleResetUser">重置</a-button>
        </a-space>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { useRouter, useRoute } from 'vue-router'
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { useLoginUserStore } from '@/stores/loginUser'
import { message } from 'ant-design-vue'
import { updateOwn, updateUser } from '@/api/userController'
import type { SelectProps } from 'ant-design-vue'
import UploadImage from '@/components/UploadImage.vue'

const selectOptions = ref<SelectProps['options']>([
  { value: 'user', label: '普通用户' },
  { value: 'admin', label: '管理员' },
])

interface props {
  userInfo?: API.UserVo
  openEditModal: boolean
  editLoading: boolean
}

interface Emits {
  (e: 'handleEditUser', userInfo: API.UserVo): void
  (e: 'update:editLoading', loading: boolean): void
  (e: 'update:openEditModal', openEditModal: boolean): void
}

const props = withDefaults(defineProps<props>(), {
  openEditModal: false,
  editLoading: false,
})
const router = useRouter()
const route = useRoute()
const loading = ref<boolean>(props.editLoading || false)
const userInfo = ref<API.UserVo>({ ...props.userInfo })
const openEditModal = ref<boolean>(props.openEditModal || false)

const emit = defineEmits<Emits>()

const loginUserStore = useLoginUserStore()

// 是否是管理员
const isAdmin = computed(() => {
  return loginUserStore.loginUser?.userRole === 'admin'
})

watch(
  [() => props.openEditModal, () => props.editLoading],
  ([val, editLoading], [prevVal, prevEditLoading]) => {
    openEditModal.value = val
    loading.value = editLoading
    if (val) {
      Object.assign(userInfo.value, props.userInfo)
    }
  },
  { deep: true },
)

const handleEditUser = async () => {
  // openEditModal.value = true
  loading.value = true
  try {
    // 解构userInfo.value中的属性
    const { id, userName, userProfile, userAvatar } = userInfo.value

    // 根据权限选择参数和接口
    const { api, params } = !isAdmin.value
      ? {
          api: updateOwn,
          params: { id, userName, userProfile, userAvatar },
        }
      : {
          api: updateUser,
          params: userInfo.value,
        }

    // 执行请求
    const res = await api(params)

    if (res.data.code === 0 && res.data.data) {
      message.success('修改成功')
      openEditModal.value = false
      emit('update:openEditModal', openEditModal.value)

      // 判断是不是修改的是当前登录用户的信息
      const isEditSelf = loginUserStore.loginUser.id === userInfo.value.id

      if (isEditSelf) {
        loginUserStore.setLoginUser(userInfo.value) // 修改当前登录用户信息
      }

      // 不是用户管理页面，就是点击了编辑个人信息按钮，逻辑上面已处理完成
      if (route.name !== 'userManage') {
        return
      }

      if (isEditSelf) {
        // 用户管理界面编辑的是当前登录用户的信息时，强制刷新页面让页面正确回显
        window.location.reload()
      } else {
        // 编辑的不是当前登录用户的信息时刷新用户列表
        emit('handleEditUser', userInfo.value)
      }
    } else {
      message.error(res.data.message)
    }
  } catch (error: any) {
    message.error(error.message)
  } finally {
    loading.value = false
  }
}

const handleCloseModal = () => {
  openEditModal.value = false
  emit('update:openEditModal', openEditModal.value)
}

const handleResetUser = () => {
  Object.assign(userInfo.value, props.userInfo)
}
</script>
